package com.example.fido2013;

import java.net.URI;
import java.util.ArrayList;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.os.AsyncTask;
import android.os.Handler;
import android.os.Message;
import android.widget.RadioGroup;
import android.app.ProgressDialog;
import android.content.Context;

public class APICallAsync extends AsyncTask<String, Integer, ArrayList> {

	HttpClient client;
	ArrayList list;
	ProgressDialog progressDialog;
	Context cont;

	String apiLocation;
	String sessionName;
	String sessionId;

	public APICallAsync(String apiLocation, String sessionName, String sessionId, Context cont) {
		this.apiLocation = apiLocation;
		this.sessionName = sessionName;
		this.sessionId = sessionId;
		this.cont = cont;
	}

	protected void onPreExecute() {
		super.onPreExecute();
		progressDialog = new ProgressDialog(cont);
		progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
		progressDialog.setMessage("Retrieving dog vests...");
		progressDialog.setCancelable(false);
		progressDialog.show();
	}

	protected ArrayList doInBackground(String... params) {
		list = new ArrayList();
		client = new DefaultHttpClient();

		try {
			URI api = new URI(apiLocation);
			HttpClient client = new DefaultHttpClient();
			HttpGet request = new HttpGet();
			request.setURI(api);

			request.setHeader("Cookie", sessionName + "=" + sessionId);

			HttpResponse response = client.execute(request);
			HttpEntity entity = response.getEntity();
			String str = EntityUtils.toString(entity);
			try {
				JSONArray JsonArrayForResult = new JSONArray(str);

				for (int i = 0; i < JsonArrayForResult.length(); i++) {
					JSONObject jsonObject = JsonArrayForResult.getJSONObject(i);
					list.add(jsonObject);
				}
			} catch (JSONException e) {
				e.printStackTrace();
				ArrayList<String> astr = new ArrayList<String>();
				astr.add(str);
				return astr;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return list;
	}

	protected void onPostExecute(ArrayList result) {

		super.onPostExecute(result);
		Message message = new Message();
		handler.sendMessage(message);
		progressDialog.dismiss();
	}

	private Handler handler = new Handler() {
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
//			progressDialog.dismiss();
		}
	};

	protected void onCancelled() {
		super.onCancelled();
	}

	public ArrayList returnList() {
		return list;
	}
}
